package com.flejay.dreamrecruiter.dao;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.xml.bind.JAXBException;

import com.flejay.dreamrecruiter.model.CurriculumVitae;
import com.flejay.dreamrecruiter.tools.CustomStringUtils;
import com.flejay.dreamrecruiter.tools.ILoggingService;
import com.flejay.dreamrecruiter.tools.converter.XmlBlocksTool;
import com.flejay.dreamrecruiter.xsd.CV;

@Singleton
@Named("fileSaverDao")
public class FileSaverDao implements ISaverDao{

	@Inject
	@Named("logService")
	private ILoggingService logService;
	
	private static final String SAVE_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\CVs\\Transformed";
	
	@Override
	public void saveExtractedCV(final CurriculumVitae cv){
		try {
			StringBuffer buf = new StringBuffer();
			buf.append(SAVE_DIRECTORY).append("\\").append(cv.getName());
			String fileName = CustomStringUtils.removeWhiteSpaceAndExtension(buf.toString()) + ".xml";
			CV cvToSave = XmlBlocksTool.convertCVIntoXml(cv.getBlockList());
			XmlBlocksTool.saveCVOnHardDrive(cvToSave, fileName);
		} catch (JAXBException e) {
			StringBuffer excMessage = new StringBuffer()
				.append("fatal error during writing file ")
				.append(cv.getName())
				.append("\n stackTrace \n")
				.append(e.getMessage());
			logService.error(this.getClass(), excMessage.toString());
			// on jete une erreur car il s'agit d'un probleme critique
			throw new IllegalStateException(excMessage.toString());
		}
	}
}
